package com.yjd.job.repayment;

import com.alibaba.edas.schedulerX.ProcessResult;
import com.alibaba.edas.schedulerX.ScxSimpleJobContext;
import com.alibaba.edas.schedulerX.ScxSimpleJobProcessor;
import com.alibaba.fastjson.JSON;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.order.model.OrderModel;
import com.yjd.comm.order.service.IOrderService;
import com.yjd.comm.repayment.model.RepaymentDataModel;
import com.yjd.comm.repayment.service.IRepaymentDataService;
import com.yjd.comm.user.model.UserModel;
import com.yjd.comm.user.service.IUserService;
import com.yjd.comm.util.*;
import com.yjd.comm.vo.Constant;
import com.yjd.comm.vo.SmsTemplate;
import org.apache.log4j.Logger;

import javax.annotation.Resource;
import java.util.List;

/**
 * 还款提醒(提前3天提醒用户还款)
 * Created by yjd-wap on 2017/11/15.
 */
public class RepaymentReminderJob implements ScxSimpleJobProcessor {

    private Logger logger = Logger.getLogger(RepaymentReminderJob.class);

    @Resource
    private IOrderService orderService;

    @Resource
    private IRepaymentDataService repaymentDataService;

    @Resource
    private IUserService userService;

    @Override
    public ProcessResult process(ScxSimpleJobContext scxSimpleJobContext) {
        try {
            int page = 1, rows = 10;
            Long currentTime = DateUtil.getCurrDateFristSecond();
            logger.info(" 还款提醒(提前3天提醒用户还款)，日期："+currentTime+"开始");

            while (true) {
                // 查找三天后需要还款的借款订单
                List<RepaymentDataModel> reminderList = (List<RepaymentDataModel>)repaymentDataService.getPageModel(
                        FrameUtil.newHashMap(
                                "page", page, "rows", rows,
                                "repayment_status", 0,
                                "estimation_repayment_time_gt", currentTime,
                                "estimation_repayment_time_le", currentTime + 259200),DbWREnums.READ).getDataList();
                if (null == reminderList || reminderList.size() == 0) {
                    break;
                }

                // 推送还款消息
                String repayment_date = null;
                String price = null;
                for (RepaymentDataModel repayment : reminderList) {
                    OrderModel order  = orderService.getModelById(repayment.getOrder_id(), DbWREnums.READ);
                    UserModel userModel = userService.getModelById(repayment.getUser_id(), DbWREnums.READ);

                    /**
                     * 资金渠道订单与其他类型订单的短信/推送信息有区别
                     */
                    if(order.getFund_channel().intValue() > 1){
                        // 获取最新还款计划
                        List<RepaymentDataModel> latest = repaymentDataService.updatePlanByOrder(order, repayment.getPeriod());
                        if(latest == null || latest.size() == 0){
                            continue;
                        }
                        RepaymentDataModel latestRepayment = latest.get(0);

                        repayment_date = DateUtil.timestampToDateString(latestRepayment.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd);
                        price = NumberUtil.formatNumber(latestRepayment.getRepayment_amount(), NumberUtil.FORMAT_4);

                        //发送短短信提醒
                        try {
                            SmsSenderUtils.smsSend(
                                    userModel.getMobile_number().toString(),
                                    SmsTemplate.getSmsTemplateMsg(SmsTemplate.SMS_REPAYMENT_MSG_FC, repayment_date, price),
                                    "");
                        } catch (Exception e) {
                            logger.error("还款报表到期短信提醒发送失败，还款信息" + JSON.toJSONString(latestRepayment) + "错误信息:" + e);
                        }

                        //发送手机推送
                        try {
                            JpushUtil.pushMessage(
                                    order.getUser_id(),
                                    Constant.SysParamKeyEnum.PUSH_TPL_REPAYMENT_REMINDER_FC,
                                    repayment_date,
                                    price);
                        } catch (Exception e1) {
                            logger.error("还款报表到期手机推送提醒发送失败，还款信息" + JSON.toJSONString(latestRepayment) + "错误信息:" + e1);
                        }

                    } else {
                        repayment_date = DateUtil.timestampToDateString(repayment.getEstimation_repayment_time(), DateUtil.PATTERN_yyyy_MM_dd);
                        price = NumberUtil.formatNumber(repayment.getRepayment_amount(), NumberUtil.FORMAT_4);

                        //发送短短信提醒
                        try {
                            SmsSenderUtils.smsSend(
                                    userModel.getMobile_number().toString(),
                                    SmsTemplate.getSmsTemplateMsg(SmsTemplate.SMS_REPAYMENT_MSG, order.getOrder_no(), price, repayment_date),
                                    "");
                        } catch (Exception e) {
                            logger.error("还款报表到期短信提醒发送失败，还款信息" + JSON.toJSONString(repayment) + "错误信息:" + e);
                        }

                        //发送手机推送
                        try {
                            JpushUtil.pushMessage(
                                    order.getUser_id(),
                                    Constant.SysParamKeyEnum.PUSH_TPL_REPAYMENT_REMINDER,
                                    price,
                                    repayment_date);
                        } catch (Exception e1) {
                            logger.error("还款报表到期手机推送提醒发送失败，还款信息" + JSON.toJSONString(repayment) + "错误信息:" + e1);
                        }
                    }

                }
                page++;
            }
            logger.info(" 还款提醒(提前3天提醒用户还款)，日期："+currentTime+"结束");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ProcessResult(true);
    }
}
